/**
 * 
 */
package edu.sjtu.seda.threadpool;

import edu.sjtu.seda.event.Event;
import edu.sjtu.seda.event.EventHandler;
import edu.sjtu.seda.event.Event.STATUS;
import edu.sjtu.seda.log.LogService;
import edu.sjtu.seda.stage.Stage;
import edu.sjtu.seda.stage.StageWrapper;

/**
 * @author john.zhu
 *
 */
public class StageRunnerImpl implements StageRunner {

	private Event event;
	private EventHandler eventHandler;
	private StageWrapper wrapper;
	
	private static LogService log = new LogService(StageRunnerImpl.class);
	
	public StageRunnerImpl(Event event,EventHandler eventHandler,StageWrapper wrapper){
		this.event = event;
		this.eventHandler = eventHandler;
		this.wrapper = wrapper;
	}
	
	/**
	 * Unit thread runner
	 * Use specific eventhandler to handle event
	 */
	@Override
	public void run() {
		log.info("event "+event.getUID()+" is running!");
		eventHandler.handle(event);
		dispatchEvent(event);
//		wrapper.getEventQueue().popEvent(event);
	}

	@Override
	public Event getEvent() {
		return this.event;
	}
	
	private void dispatchEvent(Event event){
		Stage st = event.nextLocation();
		if (st != null) {
			st.getStageWrapper().getEventQueue().pushEvent(event);
		} else {
			event.setStatus(STATUS.FINISH);
			log.info("event " + event.getUID() + " ended!");
		}
	}

}
